<template xmlns="http://www.w3.org/1999/html">
  <div>
    <div class="project" v-if="!projectAddShow && !followAddShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-if="route.name === 'WorkApply'"
          v-hasPermi="['system:workApply:query']"
          class="btn search"
          @click="getProjectList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-if="route.name === 'WorkCheck'"
          v-hasPermi="['system:workApplyCheck:query']"
          class="btn search"
          @click="getProjectList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="name">工单名称</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectName">项目名称</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectCode">项目编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="address">项目执行地</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deptName">所属部门</el-checkbox>
            </div>
            <div>
              <el-checkbox label="createUserName">申请人</el-checkbox>
            </div>

            <div>
              <el-checkbox label="createTime">提交时间</el-checkbox>
            </div>
            <div>
              <el-checkbox label="statusName">工单状态</el-checkbox>
            </div>
            
          </el-checkbox-group>
        </el-popover>
        <el-button
          v-hasPermi="['system:workApply:add']"
          class="btn add"
          v-if="route.name === 'WorkApply'"
          @click="
            projectAddShow = true;
            pageType = 'add';
          "
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >提交工单</el-button
        >
      </div>
      <el-tabs
          v-model="activeName"
          class="demo-tabs"
          @tab-change="getProjectList"
      >
        <!-- 筛选条件 -->
        <div class="search">
          <div class="search-item">
            <el-tree-select
                class="search-input"
                style="height: 100%"
                v-model="params.deptId"
                :data="deptList"
                :props="{
              value: 'deptId',
              label: 'deptName',
              children: 'children',
            }"
                value-key="deptId"
                placeholder="所属部门"
                check-strictly
                clearable
                :render-after-expand="false"
            />
          </div>

          <div class="search-item">
            <el-select
                v-model="params.projectCategory"
                placeholder="项目种类"
                clearable
                class="search-input"
            >
              <el-option
                  v-for="dict in projectCategoryList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </div>

          <div class="search-item">
            <el-select
                v-model="params.projectType"
                placeholder="项目类型"
                clearable
                class="search-input"
            >
              <el-option
                  v-for="dict in projectTypeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </div>

          <div class="search-item">
            <el-select
                v-model="params.type"
                placeholder="工单类型"
                clearable
                class="search-input"
            >
              <el-option
                  v-for="dict in typeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </div>

          <div class="search-item">
            <el-date-picker
                v-model="dateTime"
                type="daterange"
                range-separator="至"
                start-placeholder="提交开始时间"
                end-placeholder="提交结束时间"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                @change="getProjectList"
            />
          </div>
          <div class="search-item">
            <el-input
              clearable
              v-model="params.name"
              class="search-input-last"
              placeholder="请输入工单名称/项目名称/编号查询"
            ></el-input>
          </div>
        </div>
        <el-tab-pane
            :label="item.label"
            :name="item.value"
            class="demoYabs"
            v-for="item in statusList"
        ></el-tab-pane>
        <!-- 表格数据 -->
        <el-table
            v-loading="loading"
            :data="projectList"
            border
            height="58vh"
            :header-cell-style="{ 'text-align': 'center' }"
        >
          <!-- 操作模式 -->
          <el-table-column
              label="操作"
              :show-overflow-tooltip="true"
              :width="route.name === 'WorkApply' ? '180px' : '140px'"
          >
            <template #default="{ row }">
              <div class="table-operate">
                <el-icon
                    v-if="route.name === 'WorkApply'"
                    v-hasPermi="['system:workApply:detail']"
                    title="查看详情"
                    color="#007CEF"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('detail', row)"
                >
                  <Document />
                </el-icon>
                <el-icon
                    v-if="route.name === 'WorkCheck'"
                    v-hasPermi="['system:workApplyCheck:detail']"
                    title="查看详情"
                    color="#007CEF"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('detail', row)"
                >
                  <Document />
                </el-icon>
                <el-icon
                    v-hasPermi="['system:workApply:acceptance']"
                    title="受理"  v-if="[0].includes(row.status)"
                    color="#007CEF"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('acceptance', row)"
                >
                  <!-- <Notification /> -->
                  <img
                  src="@/assets/icons/images/accept.png"
                  style="width: 18px; height: 18px"
                />
                </el-icon>
                <el-icon
                    v-hasPermi="['system:workApply:back']"
                    title="退回"  v-if="[0].includes(row.status)"
                    color="#007CEF"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('back', row)"
                >
                  <!-- <Back /> -->
                  <img
                  src="@/assets/icons/images/back.png"
                  style="width: 18px; height: 18px"
                />
                </el-icon>
                <el-icon
                    v-hasPermi="['system:workApply:allocation']"
                    title="分配"
                    color="#007CEF"
                    class="table-icon"
                    :size="20"          v-if="[1].includes(row.status)"
                    @click="handleOperate('allocation', row)"
                >
                  <img
                      src="@/assets/icons/images/allot.png"
                      style="width: 17px; height: 17px"
                  />
                </el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column
              type="index"
              label="序号"
              :index="indexMethod"
              width="70"
              align="center"
          />
          <el-table-column
              label="工单名称"
              prop="name" v-if="checkList.includes('name')"
              :show-overflow-tooltip="true"
              width="220"
          />
          <el-table-column
              label="项目名称"
              prop="projectName" v-if="checkList.includes('projectName')"
              :show-overflow-tooltip="true"
              width="220"
          >
            <template #default="{ row }">
              <span>{{ row.projectName ? row.projectName : "--" }}</span>
            </template>
          </el-table-column>
          <el-table-column
              label="项目编号"
              prop="projectCode" v-if="checkList.includes('projectCode')"
              :show-overflow-tooltip="true"
              min-width="200"
          />
          <el-table-column
              label="项目执行地"
              prop="address" v-if="checkList.includes('address')"
              :show-overflow-tooltip="true"
              width="200"
          />
          <el-table-column
              label="所属部门"
              prop="deptName" v-if="checkList.includes('deptName')"
              :show-overflow-tooltip="true"
              min-width="140"
          />
          <el-table-column
              label="工单类型"
              prop="typeName" v-if="checkList.includes('typeName')"
              :show-overflow-tooltip="true"
              width="100"
          >
            <template #default="{ row }">
              <span>{{
                  row.typeName ? row.typeName : "--"
                }}</span>
            </template>
          </el-table-column>
          <el-table-column
              label="申请人"
              prop="createUserName" v-if="checkList.includes('createUserName')"
              :show-overflow-tooltip="true"
              width="100"
          >
            <template #default="{ row }">
              <span>{{ row.createUserName ? row.createUserName : "--" }}</span>
            </template>
          </el-table-column>
          <el-table-column
              label="提交时间"
              prop="createTime" v-if="checkList.includes('createTime')"
              :show-overflow-tooltip="true"
              min-width="140"
          />
          <el-table-column
              label="工单状态"
              prop="statusName" v-if="checkList.includes('statusName')"
              :show-overflow-tooltip="true"
              width="100"
          >
            <template #default="{ row }">
              <span :style="getStatusColor(row.statusName)">{{
                  row.statusName ? row.statusName : '--'
                }}</span>
            </template>
          </el-table-column>

        </el-table>

        <!-- 分页 -->
        <pagination
            class="pagination"
            :total="total"
            v-model:page="params.pageNum"
            v-model:limit="params.pageSize"
            @pagination="getProjectList"
        />

      </el-tabs>
    </div>
    <ProjectAdd
      v-if="projectAddShow"
      ref="projectAddRef"
      v-model:projectAddShow="projectAddShow"
      @updateFollowAddShow="followAddShow = false"
      @refreshList="getProjectList"
      :pageType="pageType"
    />
    <FollowAdd
      ref="followAddRef"
      v-model:followAddShow="followAddShow"
      @refreshList="getProjectList"
      :pageType="pageType"
      v-if="followAddShow"
    />

    <!--  工单受理  -->
    <el-dialog
        :title="'操作提示'"
        v-model="acceptanceShow"
        width="600px"
        append-to-body
    >
   <div style="display:flex;">
    <div>
      <img src="../../../assets/images/none-icon.png" style="width: 249px;
    height: 209px;" alt="">
    </div>
      <div>
        <div class="dialog-title-accep">
        确认受理该工单？
      </div>
      <div class="dialog-title2">受理后不可修改！</div>
      </div>
   </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
              style="color: #fff; background-color: rgba(67, 207, 124, 1)"
              @click="saveCheck('followAdd')"
              v-loading="loadingCheck"
          >确 认</el-button
          >
          <el-button style="background-color: #fff" @click="acceptanceShow = false"
          >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!--  工单退回  -->
    <el-dialog
        :title="'操作提示'"
        v-model="orderReturnShow"
        width="600px"
        append-to-body
    >
      <div class="dialog-title">
        <Warning
            style="width: 18px; height: 18px; margin-right: 8px; color: #d95700"
        />
        <span style="color: #d95700">工单退回后不可再次发起！</span>
      </div>
      <!-- <el-form-item label="情况说明：" label-width="90"> -->
      <div style="display: flex">
        <div style="width: 100px">
          <span style="color: red">*</span> 退回原因：
        </div>
        <el-input
            style="width: 100%"
            v-model="auditRemark"
            placeholder="请填写"
            type="textarea"
            maxlength="500"
            clearable
            show-word-limit
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button
              style="color: #fff; background-color: rgba(67, 207, 124, 1)"
              @click="saveCheck('orderReturn')"
              v-loading="loadingCheck"
          >保存</el-button
          >
          <el-button style="background-color: #fff" @click="cancelOrder('orderReturn')"
          >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!--  分配  -->
    <el-dialog
        :title="'任务分配'"
        v-model="taskAllocationShow"
        width="800px"
        append-to-body
    >
      <div class="project-info" style="min-height:400px;">
        <el-form
            :model="projectForm"
            ref="projectFormRef"
            :rules="queryRules"
            label-width="120px"
            v-enterToNext
            :disabled="pageType === 'detail' || pageType === 'check'"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item
                  label="计划开始时间："
                  prop="startTime"
                  label-width="120"
              >
                <el-date-picker
                    v-model="projectForm.startTime"
                    type="date"
                    placeholder="请选择"
                     format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    @change="handleTimeChange(1)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                  label="计划结束时间："
                  prop="endTime"
                  label-width="120"
              >
                <el-date-picker
                    v-model="projectForm.endTime"
                    type="date"
                    placeholder="请选择"
                     format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    @change="handleTimeChange(2)"
                    :default-time="new Date(2000, 1, 1, 23, 59, 59)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="责任人员：" prop="userList">
                <el-select
                    filterable
                    style="width: 100%;height:100%;"
                    v-model="projectForm.userList"
                    multiple
                    placeholder="请选择"
                    clearable
                    @change="userListChange"
                    class="search-input"
                >
                  <el-option key="0" label="" value="" disabled>
                    <span style="float: left; color: #8492a6">人员姓名</span>
                    <span style="margin: 0 80px 0 50px; color: #8492a6"
                    >联系方式</span
                    >
                    <span
                        style="
                          margin: 0 100px 0 0px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                    >职位</span
                    >
                    <span style="color: #8492a6; font-size: 13px">部门</span>
                  </el-option>
                  <el-option
                      v-for="item in userList"
                      :key="item.userId"
                      :label="item.nickName"
                      :value="item.userId"
                  >
                      <span
                          style="display: inline-block; width: 80px; float: left"
                      >{{ item.nickName }}</span
                      >
                    <span
                        style="
                          display: inline-block;
                          width: 125px;
                          margin: 0 15px 0 23px;
                          color: #8492a6;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                    >{{ item.phonenumber ? item.phonenumber : "--" }}</span
                    >
                    <span
                        style="
                          display: inline-block;
                          width: 125px;
                          font-size: 13px;
                          margin: 0 0px 0 0px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                    >
                        {{ item.postName ? item.postName : "--" }}
                      </span>
                    <span
                        style="
                          display: inline-block;
                          margin: 0 0px 0 0px;
                          font-size: 13px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                    >
                        {{ item.fullDeptName ? item.fullDeptName : "--" }}
                      </span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <div v-if="personnelTableVisible">
            <el-table
                v-loading="loading"
                :data="allocationList"
                border
                height="50vh"
                width="100%"
                style="margin-bottom: 10px"
                :header-cell-style="{ 'text-align': 'center' }"
            >
              <el-table-column
                  label="姓名"
                  prop="userName"
                  width="140"
                  align="center"
              />
              <el-table-column
                  label="待开始任务"
                  prop="cnt0"
                  width="150"
                  align="center"
              />
              <el-table-column
                  label="进行中任务"
                  prop="cnt1"
                  width="150"
                  align="center"
              />
              <el-table-column
                  label="已逾期任务"
                  prop="cnt2"
                  width="150"
                  align="center"
              />
              <el-table-column
                  label="操作"
                  width="170"
                  align="center"
              >
                <template #default="{ row, $index }">
                  <el-icon
                      title="查看详情"
                      color="#007CEF"
                      class="table-icon"
                      :size="20"
                      @click="handlePersonTable('detail', row)"
                  >
                    <Document />
                  </el-icon>
                  <el-icon
                      title="删除"
                      color="#E33838"
                      class="table-icon"
                      :size="20"
                      @click="handlePersonTable('delete', row, $index)"
                  >
                    <Delete />
                  </el-icon>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-row>
            <el-col :span="24">
              <el-form-item
                  label="任务内容："
                  prop="remark"
                  label-width="120"
              >
                <el-input
                    v-model="projectForm.remark"
                    type="textarea"
                    maxlength="500"
                    placeholder="请填写"
                    show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
              style="color: #fff; background-color: rgba(67, 207, 124, 1)"
              @click="allocationCheck(projectFormRef)"
              v-loading="loadingCheck"
          >保存</el-button
          >
          <el-button style="background-color: #fff" @click="clearAllocation"
          >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
    <!--  个人任务  -->
    <el-dialog
        :title="'个人任务'"
        v-model="personalTasksShow"
        width="800px"
        append-to-body
    >
      <div class="task-container">
        <div class="task-container-left">
          <div>{{ infoPersonName }}</div>
          <div style="font-size: 16px;">{{ infoDeptName }}</div>
        </div>
        <div style="display: flex">
          <div
              class="personTask"
              v-for="(item, index) in personStatusList"
              :style="index === 0 ? 'background: rgb(240,248,244)' : index === 1 ? 'background: rgb(240,250,254)' : 'background: rgb(254,235,227)'">
            <span class="task-label">{{ item.label }}</span>
            <span class="task-number" :style="index == 0 ? 'color: green' : index == 1 ? 'color: blue' : 'color: red'">{{ item.number }}</span>
            <span class="task-label">个</span>
          </div>
        </div>
      </div>
      <div class="task-table">
        <div class="task-table-card" v-for="item in taskProjectList">
          <div class="task-content task-border" style="margin-top:0px;">
            <div class="task-border">
              <span>【{{ item.missionStatusName }}】</span>&nbsp;&nbsp;
              <span>{{ item.projectName }}</span>
            </div>
            <div class="timeConflict" v-if="item.status && item.missionTypeStatusName != '已完成'">时间段冲突</div>
          </div>
          <div class="task-content task-border">
            <div>
              <span>项目任务名称：</span>
              <span>{{ item.missionTypeName  || '--'}}</span>
            </div>
            <div>
              <span>任务状态：</span>
              <span>{{ item.missionTypeStatusName }}</span>
            </div>
          </div>
          <div class="task-content task-border">
            <div>
              <span>计划开始时间：</span>
              <span>{{ item.startTime }}</span>
            </div>
            <div>
              <span>计划结束时间：</span>
              <span>{{ item.endTime }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!--  工单详情  -->
    <ProjectDetail
        v-if="workOrderDetailShow"
        ref="projectCheckRef"
        v-model:projectAddShow="workOrderDetailShow"
        @updateFollowAddShow="followAddShow = false"
    />
  </div>
</template>

<script setup>
import FollowAdd from "./followAdd.vue";
import ProjectAdd from "./projectAdd.vue";
import { getProjectListApi, deleteProjectApi } from "@/api/sales/project";
import { listDeptAll } from "@/api/system/dept";
import {
  getWorkApplyListApi,
  getWorkOrderAffirmApi,
  getWorkOrderBackApi,
  getUserListApi, orderCntApi, allotListApi, getOrderCntDtlApi
} from "@/api/operation/work";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import ProjectDetail from "@/views/operation/workApply/projectDetail.vue";
const activeName = ref(99);
const workOrderTabs = ref(0);

const { proxy } = getCurrentInstance();
// 路由
const route = useRoute();
// 搜索参数
const params = reactive({
  deptId: null, // 部门id
  projectCategory: null, // 项目种类
  projectType: null, // 项目类型
  name: "", // 工单名称
  type: null, // 工单类型
  status: null, // 状态
  beginDate: "", // 开始时间
  endDate: "", // 结束时间
  pageNum: 1,
  pageSize: 50,
});
// 表格加载效果
const loading = ref(false);
// 项目新增组件显隐
const projectAddShow = ref(false);
// 跟进新增组件显隐
const followAddShow = ref(false);
// 项目列表
const projectList = ref([]);
// 总数
const total = ref(0);
// 项目新增组件引用
const projectAddRef = ref(null);
// 跟进组件引用
const followAddRef = ref(null);
// 操作类型
const pageType = ref("");
// 项目种类列表
const projectCategoryList = ref([]);
// 项目类型
const projectTypeList = ref([]);
// 是否签合同列表
const contractList = ref([]);
// 项目状态列表
// const statusList = ref([]);
// 项目类型列表
const typeList = ref([]);
// 工单受理弹窗
const acceptanceShow = ref(false);
const loadingCheck = ref(false);
// 工单退回
const orderReturnShow = ref(false);
// 任务分配弹窗
const taskAllocationShow = ref(false);
// 选择责任人员显示的表格
const personnelTableVisible = ref(false);
const personalTasksShow = ref(false);
// 任务分配对象
const projectForm = ref({
  startTime: "",
  endTime: "",
  userList: [],
  remark: ''
});
const queryRules = ref({
  startTime: [
    { required: true, message: "请选择计划开始时间", trigger: "blur" },
  ],
  endTime: [
    { required: true, message: "请选择计划结束时间", trigger: "blur" },
  ],
  userList: [
    { required: true, message: "请选择责任人员", trigger: "blur" },
  ]
})

const checkList = ref([
  "name",
  "projectName",
  "projectCode",
  "address",
  "deptName",
  "typeName",
  "createUserName",
  "createTime",
  "statusName",
]);

const personStatusList = ref([])
// 部门类型列表
const deptList = ref([]);
// 状态列表
const statusList = ref([]);
// 时间筛选
const dateTime = ref('');
// 退回原因
const auditRemark = ref('');

const taskProjectList = ref([])

// 工单详情弹窗
const workOrderDetailShow = ref(false);
// 责任人员下拉列表
const userList = ref([]);
// 任务分配表单ref
const projectFormRef = ref();
// 任务分配表单
const allocationList = ref([]);
const projectCheckRef = ref();

/**
 * @description: 复选框选中
 */
 const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType: 61,
    titleField: str,
  });
};

/**
 * @description: 获取表头
 */
 const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: 61,
  });
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 获取用户列表
 */
const getUserList = async () => {
  await getUserListApi(2).then((res) => {
    if (res) {
      userList.value = res;
    }
  });
};

/**
 * @description: 重置
 */
const handleRefresh = () => {
  Object.assign(params, {
    deptId: null, // 部门id
    projectCategory: null, // 项目种类
    projectType: null, // 项目类型
    name: "", // 工单名称
    type: null, // 工单类型
    status: null, // 状态
    beginDate: "", // 开始时间
    endDate: "", // 结束时间
    pageNum: 1,
    pageSize: 50,
  });
  getProjectList();
};

/**
 * @description: 获取项目列表
 */
const getProjectList = async () => {
  params.status = activeName.value;
  params.beginDate = !!dateTime.value ? dateTime.value[0] : '';
  params.endDate = !!dateTime.value ? dateTime.value[1] : '';
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    let res;
    res = await getWorkApplyListApi({ pageNum, pageSize }, params);
    projectList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
var acceptanceId = ""; // 获取的受理id
var allocationObj = null; // 点击获取的列表信息
const handleOperate = async (type, row) => {
  switch (type) {
    case "detail":
      workOrderDetailShow.value = true;
      nextTick(() => {
        projectCheckRef.value.handleDetailInfo(row.id);
      })
      break;
    case "acceptance": // 受理
      acceptanceShow.value = true;
      acceptanceId = row.id;
      break;
    case "back": // 退回
      orderReturnShow.value = true;
      auditRemark.value = "";
      acceptanceId = row.id;
      break;
    case "allocation": // 分配
      taskAllocationShow.value = true;
      allocationObj = row;
      break;
    default:
      break;
  }
};

/*
* 工单详情切换
* */
const getWorkChange = () => {

}

/*
* 工单受理弹窗保存
* */
const saveCheck = (type, projectFormRef) => {
  switch (type) {
    case 'followAdd':
      loadingCheck.value = true;
      getWorkOrderAffirmApi({id: acceptanceId}).then(res => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          acceptanceShow.value = false;
          getProjectList();
          loadingCheck.value = false;
        }
      })
      break;
    case 'orderReturn':
      if (auditRemark.value === null || auditRemark.value === "") {
        ElMessage.error("退回原因不能为空");
        return;
      }
      loadingCheck.value = true;
      let params = {
        id: acceptanceId,
        backremark: auditRemark.value
      }
      getWorkOrderBackApi(params).then(res => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          getProjectList();
          loadingCheck.value = false;
          cancelOrder(type)
        }
      })
      break;
    default:
      break;
  }
}


/*
* 取消工单受理/工单退回
* */
const cancelOrder = (type) => {
  switch (type) {
    case 'orderReturn':
      auditRemark.value = '';
      orderReturnShow.value = false;
      break;
  }
}

/*
* 任务分配表单提交
* */
const allocationCheck = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let params = {
        ...projectForm.value,
        id: allocationObj.id,
        projectId: allocationObj.projectId
      }
      allotListApi(params).then(res => {
        if (res.code === 200) {
          clearAllocation();
          getProjectList();
          ElMessage.success(res.msg);
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

/*
* 任务分配取消
* */
const clearAllocation = () => {
  taskAllocationShow.value = false;
  projectForm.value = {
    startTime: "",
    endTime: "",
    userList: [],
    remark: ''
  }
  allocationList.value = [];
  personnelTableVisible.value = false;
}

/*
* 根据责任人筛选查询表格
* */
const userListChange = (value) => {
  if (value.length > 0) {
    personnelTableVisible.value = true;
    let params = {
      userIds: value
    }
    orderCntApi(params).then(res => {
      if (res) {
        allocationList.value = res
      }
    })
  }else {
    personnelTableVisible.value = false;
  }
}

/**
 * @description: 处理时间变更
 */
 const handleTimeChange = (flag) => {
  if (projectForm.value.startTime && projectForm.value.endTime &&projectForm.value.startTime > projectForm.value.endTime) {
    ElMessage.info("计划开始时间不能大于计划结束时间！");
    if (flag == 1) {
      projectForm.value.startTime = "";
    } else {
      projectForm.value.endTime = "";
    }
  }
};


/*
*
* 时间戳转换*/
const nowDate = (now) => {
  const date = new Date(now)
  const time = date.getTime() // 精确到毫秒
  return time;
}

/*
* 责任人员表格操作按钮
* */
let infoPerson = null;
let infoPersonName = "";
let infoDeptName = "";
const handlePersonTable = (type, row, index) => {
  switch (type) {
    case 'detail':
      infoPerson = row;
      personalTasksShow.value = true;
      personStatusList.value = [
        {
          label: '待开始',
          number: row.cnt0
        },
        {
          label: '进行中',
          number: row.cnt1
        },
        {
          label: '已逾期',
          number: row.cnt2
        }
      ]
      getOrderCntDtlApi({userId: row.userId }).then(res => {
        if (res) {
          taskProjectList.value = res
          infoPersonName = taskProjectList.value[0].userName;
          infoDeptName = taskProjectList.value[0].deptName;
          let startTime = null;
          let endTime = null;
          if (!!projectForm.value.startTime || !!projectForm.value.endTime) {
            startTime = nowDate(projectForm.value.startTime);
            endTime = nowDate(projectForm.value.endTime);
          }else{
            startTime = null;
            endTime = null;
          }
          taskProjectList.value.map(item => {
            let actionStatTime = nowDate(item.startTime)
            let actionEndTime = nowDate(item.endTime)
            if (!!startTime || !!endTime) {
              if (startTime >= actionStatTime && startTime <= actionEndTime) {
                item.status = true;
              }else if (endTime >= actionStatTime && startTime <= actionEndTime) {
                item.status = true;
              }
            }else {
              item.status = false;
            }
          })
        }
      })
      break;
    case 'delete':
      allocationList.value.splice(index, 1);
      projectForm.value.userList = projectForm.value.userList.filter(item => item != row.userId)
      break;
    default:
      break;
  }
}

/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("erp_project_category").then((res) => {
    // 项目种类
    if (res.code === 200) {
      projectCategoryList.value = res.data;
    }
  });

  await getDictsApi("erp_project_type").then((res) => {
    // 项目类型
    if (res.code === 200) {
      projectTypeList.value = res.data;
    }
  });
  await getDictsApi("erp_work_order_type").then((res) => {
    // 工单类型
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });
  await getDictsApi("erp_workorder_status").then((res) => {
    // 状态
    if (res.code === 200) {
      statusList.value = res.data;
      statusList.value.unshift({
        label: '全部',
        value: 99
      })
    }
  });
  //部门
  listDeptAll().then((response) => {
    deptList.value = proxy.handleTree(response.data, "deptId");
  });
}

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

onMounted(() => {
  // 路由携带项目id参数，直接显示详情页
  if (route.query?.workOrderId) {
    let workOrderId = route.query.workOrderId;
    pageType.value = "detail";
    projectAddShow.value = true;
    nextTick(() => {
      projectAddRef.value.handleDetailInfo(workOrderId);
    });
  }
  if (route.query?.businessId) {
    let applyId = route.query.businessId;
    if (
      route.query.checkStatus === "待审核" ||
      route.query.checkStatus === "审核中"
    ) {
      pageType.value = "check";
      projectAddShow.value = true;
      nextTick(() => {
        projectAddRef.value.handleDetailInfo(Number(applyId));
      });
    }
  }
  if (route.query?.myinfoId) {
    let applyId = route.query.myinfoId;
    pageType.value = "detail";
    projectAddShow.value = true;
    nextTick(() => {
      projectAddRef.value.handleDetailInfo(Number(applyId));
    });
  }
  getTableHeader();
  getProjectList();
  getDicts();
  getUserList();
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.project {
  padding: 20px;
  width: 100%;
  height: 100%;
  .search-item {
    // margin-bottom: 20px;
  }
  :deep(.el-tabs__item.is-top) {
    //width: 97px;

    font-size: 16px;
  }
  .search-input-last{
    width: 250px;
  }
  .pagination {
    margin-top: 20px;
  }
  .pagination-container{
    height: 53px;
  }
}
.dialog-title-accep{
  margin-top:40px;
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  padding-left: 20px;
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 600;
}
.dialog-title2{
  padding-left: 20px;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 500;
}
.dialog-title {
  background-color: #fdefdc;
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  padding-left: 20px;
  margin-bottom: 20px;
}
.task-container{
  width: 100%;
  //border: 1px red solid;
  display: flex;
  justify-content: space-between;
  .task-container-left{
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;

    div:first-child{
      font-weight: 600;
      font-size: 24px;
      color: black;
    }
  }
}
.task-table{
  width: 100%;
  height: 61vh;
  overflow: hidden;
  overflow-y: scroll;
  margin-top: 20px;
  .task-table-card{
    width: 100%;
    height: 185px;
    border: 1px rgb(215, 215, 215) solid;
    border-radius: 10px;
    padding: 0px 15px;
    font-size: 15px;
    margin-bottom: 20px;
    .task-border{
      margin-top: 30px;
    }
    .task-content{
      display: flex;
      justify-content: space-between;
    }
    .timeConflict{
      margin-top:20px;
      width: 120px;
      height: 45px;
      color: rgb(247, 98, 128);
      background: rgb(254, 244, 231);
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.personTask{
  width: 140px;
  height: 110px;
  border-radius: 10px;
  margin: 0 10px;
  display: flex;
  align-items: center;
  justify-content: center;

  .task-label{
    font-size: 16px;
    color: black;
  }

  .task-number{
    font-size: 20px;
    font-weight: 700;
  }
}

</style>
